<template>
	<om-addpage style="padding-top: 35px;" :busCode="busCode" :menuName="menuName" @formSubmit="formSubmit" :showHistoryBtn="true">
		<om-autoform ref="autoform" :checkedit="checkedit"  :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
	</om-addpage>
</template>
<script>
	import {
		buildFormData,
		formValidation,
		changeEditor,
		formShowLoading,
		configFormEditor,
		getEditorTitle,
		getWorkCacheKey,
		changeConfigAttr,
		configSelectData,
		formModelLoad,
		getFormFields,
		hasEditor
	} from '@/static/js/formUtil.js';
	import { errorModal, confirmModal } from '@/static/js/common.js'
	import dateTimePicker from '@/static/js/dateTimePicker.js';
	import urlUtil from '@/static/js/urlUtil.js';
	import { mapState } from 'pinia';
	import {useLoginUserStore} from '@/stores/login-user.js';
export default {
	provide() {
		return {
			formPage: this
		};
	},
	data() {
		return buildFormData({
			userCacheKey:'hr-u-officeadjust-user-cache',
			instCacheKey:'hr-u-officeadjust-inst-cache',
			posListStr:''
		})
	},
	computed: {
		...mapState(useLoginUserStore, ['userName', 'userId'])
	},
	methods: {
		verifyUser1(){
			let _that = this
			if(!_that.$refs.autoform.formdata.zposId){
				_that.om.toast("请先选择制表岗位")
				return false
			}else{
				return true
			}
		},
		onInputProbation(num){
			if(this.formdata.entryDate){
				var d1 = this.moment(this.formdata.entryDate)
				var probationDate = d1.add(num, "days").format("YYYY-MM-DD")
				this.$refs.autoform.formdata.probationDate = probationDate
			}else if(this.formdata.probationDate){
				var d2 = this.moment(this.formdata.probationDate)
				var entryDate = d2.subtract(num, "days").format("YYYY-MM-DD")
				this.$refs.autoform.formdata.entryDate = entryDate
			}
		},
		onSelectEntryDate(item){
			var d1 = this.moment(item)
			if(this.formdata.probationDate){
				var d2 = this.moment(this.formdata.probationDate)
				var diff = d2.diff(d1, 'days')
				this.$refs.autoform.formdata.probation = diff
			}else if(this.formdata.probation){
				var probationDate = d1.add(this.formdata.probation, "days").format("YYYY-MM-DD")
				this.$refs.autoform.formdata.probationDate = probationDate
			}
		},
		//计算试用期到期日
		onSelectProbationDate(item){
			var d2 = this.moment(item)
			if(this.formdata.entryDate){
				var d1 = this.moment(this.formdata.entryDate)
				var diff = d2.diff(d1, 'days')
				this.$refs.autoform.formdata.probation = diff
			}else if(this.formdata.probation){
				var entryDate = d2.subtract(this.formdata.probation, "days").format("YYYY-MM-DD")
				this.$refs.autoform.formdata.entryDate = entryDate
			}
		},
		formSubmit() {
			var formdata = {}
			for(var e in this.formdata){
				if(this.formdata[e]){
					formdata[e] = this.formdata[e]
				}
			}
			this.om.formSave('tempPosAdjust/addTempPosAdjust', formdata, this);
		},
		verifyUser(userId) {
			let _that = this;
			this.om.request("tempPosAdjust/verifyUser", {
				userId:userId
			}).then(res => {
				if(res.succeed) {
					if(res.value){
						if (res.value.one) {
							errorModal(_that,"提示信息",res.value.one,function(){
								_that.$refs.autoform.clear("userInfo","userId")
							})
						}else if (res.value.two){
							confirmModal(_that,"提示信息",res.value.two,function(){
								_that.setUserInfo(userId)
							},function(){
								_that.$refs.autoform.clear("userInfo","userId")
							})
						} else {
							_that.setUserInfo(userId)
						}
					}
				}else{
					_that.om.toast(res.msg)
				}
			})
		},
		setUserInfo(userId){
			let _that = this;
			this.om.request("tempPosAdjust/setInfo", {
				userId:userId
			}).then(res => {
				if(res.succeed) {
					if(res.value){
						var info = res.value.tempPosAdjust
						var origInfoEditor = _that.subEditorObj['origInfo']
						origInfoEditor.workList = res.value.origs
						_that.loadOrg()
						_that.loadSalaryPos()
						Object.assign(_that.$refs.autoform.formdata,info,_that.$refs.autoform.formdata,res.value.salaryResponse)
						
					}
				}else{
					_that.om.toast(res.msg)
				}
			})
		},
		loadSalaryPos(){//任职岗位不变
			let _that = this;
			var origInfo = _that.subEditorObj['origInfo']
			var newInfo = _that.subEditorObj['newInfo']
			var posIds = []
			if(origInfo.workList.length){
				posIds = origInfo.workList.filter(e=>e.origHandleWayCode && e.origHandleWayCode == '35511').map(e=>e.origPosId)
			}
			if(newInfo.workList.length){
				var newPosArr = newInfo.workList.map(e=>e.newPosId)
				posIds = [...posIds, newPosArr]
			}
			this.om.request("tempPosAdjust/getSalaryPosList",{
				posIds:posIds.join(",")
			}).then(res=>{
				_that.$refs.autoform.changeEditor('title10', 'salaryPosId', 'data', configSelectData(res, 'id', 'posname'));
				_that.$refs.autoform.initSelectIndex('title10', 'salaryPosId')
			})
		},
		onSelectSalaryPos(item){
			this.$refs.autoform.formdata.salaryWay1 = item.salarycatName
			this.$refs.autoform.formdata.posGrade1 = item.careercatName
		},
		clearSalaryPos(){
			this.$refs.autoform.clear('title10', 'salaryPosId')
			this.$refs.autoform.clear('title10', 'salaryWay1')
			this.$refs.autoform.clear('title10', 'posGrade1')
		},
		loadOrg(){
			let _that = this;
			this.om.request("tempInstAdjust/getOrgList",{
				zposId:this.formdata.zposId
			}).then(res=>{
				if(Array.isArray(res)){
					_that.$refs.autoform.changeEditor("instInfo","newOrgId",{
						data: configSelectData(res,"id","shortname")
					})
					if(res.length == 1) {
						_that.$refs.autoform.initSelectIndex("instInfo","newOrgId",res[0].id)
						_that.onSelectOrg(res[0])
					}else{
						_that.$refs.autoform.initSelectIndex("instInfo","newOrgId")
					}
				}
			})
		},
		onSelectOrg(item){
			let _that = this;
			this.$refs.autoform.changeEditor("instInfo", "newInstId", {
				type:'linkbox',
				link: '../../public/search/search',
				linkParam: {
					other:JSON.stringify({
						orgId: item.id
					}),
					searchfield:'q',
					valuefield: 'id',
					namefield: 'instname',
					initload:true,
					url: 'tinstitution/findNotAll',
					cachename: _that.instCacheKey,
					placeholder:'请输入机构名称'
				}
			})
		},
		verifyInst(instId){
			let _that = this
			this.om.request("tempInstAdjust/verifyInst",{
				instId:instId
			}).then(res=>{
				if(res.succeed){
					if(res.value){
						errorModal(_that,"提示信息",res.value,function(){
							_that.$refs.autoform.clear("instInfo","newInstId")
						})
					}else{
						_that.verifyInst1(instId);
					}
				} else {
					_that.om.toast(res.msg)
				}
			})
		},
		verifyInst1(instId){
			let _that = this
			this.om.request("hrPosUtil/getTipAfterUser",{
				instId:instId,
				formCode:_that.busCode,
				userId:_that.formdata.userId,
				zposId:_that.formdata.zposId
			}).then(res=>{
				if(res.succeed){
					if(!res.value){
						_that.om.toast("没有可选的岗位")
					}
				} else {
					_that.om.toast(res.msg)
				}
			})
		},
		verifyOpenNewInfo(){
			if(!this.formdata.newInstId){
				return '请选择拟调入机构'
			}
			if(!this.posListStr){
				return '没有可选的岗位'
			}
			var origWorkList = this.subEditorObj['origInfo'].workList
			if(origWorkList.length){
				var filterList = origWorkList.filter(e=>!e.origHandleWayCode);
				if(filterList.length){
					return '请先选择' + getEditorTitle('origInfo','origHandleWayCode',this.subConfigData['origInfo'])
				}
			}
			
			return true
		},
		getNewInfoParam(){
			var attr = {
				instId:this.formdata.newInstId,
				posListStr:this.posListStr,
				adjustUserId:this.formdata.userId
			}
			
			var editor1 = this.subEditorObj['origInfo']
			if(editor1.workList.length){//
				var list = editor1.workList.filter(e=>e.origHandleWayCode == '35516')
				if(list.length == editor1.workList.length){
					attr.isallNoOfficeFlag = true
				}
				var list2 = editor1.workList.filter(e=>e.origHandleWayCode != '35516')
				if(list2.length){
					var posIdsStr = list2.map(e=>e.origPosId).join(',')
					attr.posIdsStr = posIdsStr
				}
			}
			
			var editor = this.subEditorObj['newInfo'] 
			if(editor.workList.length){
				attr.existPosIdStr = editor.workList.map(e=>e.newPosId).join(",")
				var list = editor.workList.map(e=>e.newReasonCode == '23753');
				attr.hasUserStoreFlag = list.length>0
				attr.hasDataFlag = true
			}
			return attr
		},
		onSelectSalaryLevel(item){
			let _that = this
			this.om.request("salaryStandard/getSalaryRange1",{
				levelId:item.id,
				posId:_that.formdata.salaryPosId
			}).then(res=>{
				if(res.succeed){
					if(res.value && res.value.str){
						_that.$refs.autoform.formdata.levelSalaryRange = res.value.str
					}
				} else {
					_that.om.toast(res.msg)
				}
			})
		},
		clearSalaryLevel(){
			this.$refs.autoform.clear('title10','salaryLevelId')
			this.$refs.autoform.clear('title10','levelSalaryRange')
		},
		
		initLoad(options) {
			let _that = this;
			var ajaxArr = [
				urlUtil.zposUrl(options.code), //制表岗位
				urlUtil.dataDictInitValueUrl('DD014009001'), //调薪开始日期约束
				urlUtil.sysdictComboboxUrl('23645'),//薪资档级
			];
			var fileId = options.fileId
			if(fileId){
				ajaxArr.push({
					url:"tempPosAdjust/getInfo",
					param:{id:fileId}
				})
			}
			formModelLoad(ajaxArr, function(res, mainData) {
				changeEditor('topinfo', 'zposId', 'data', configSelectData(res[0], 'id', 'posname'), mainData);
				changeEditor('title10', 'salaryLevelId', 'data', configSelectData(res[2], 'id', 'dicname'), mainData);
				changeEditor('userInfo','userId',{//调整人员信息
					link: '../../public/pageSearch/pageSearch',
					linkParam: {
						searchfield:'q',
						namefield: 'username',
						url: "tempPosAdjust/getComboboxAll",
						cachename: _that.userCacheKey,
						placeholder: '请输入姓名'
					}
				}, null, mainData);
				
				if (_that.subConfigData['origInfo']) {
					var configData = _that.subConfigData['origInfo']
					var attr = {
						showAdd:false,
						showDel:false
					}
					if(hasEditor('origInfo','origPosId',configData)){
						attr.titleTemplate = '<%= origPosName %>'
					}
					if(hasEditor('origInfo','origWorkTypeCode',configData)){
						attr.subtitle1Template = '任职方式: <%= origWorkTypeName %>'
					}
					if(hasEditor('origInfo','origWorkDate',configData)){
						attr.subtitle2Template = '上岗日期: <%= origWorkDate %>'
					}
					if(hasEditor('origInfo','origHandleWayCode',configData)){
						attr.subtitle3Template = '原岗位处理方式: <%= origHandleWayName || "无" %>'
					}
					changeEditor('origInfo', 'objStr1', attr, mainData);
				}
				if (_that.subConfigData['newInfo']) {
					var configData = _that.subConfigData['newInfo']
					var attr = {
						verifyfunc:'verifyOpenNewInfo',
						getWorkParam:'getNewInfoParam'
					}
					if(hasEditor('newInfo','newPosId',configData)){
						attr.titleTemplate = '<%= newPosName %>'
					}
					if(hasEditor('newInfo','newReasonCode',configData)){
						attr.subtitle1Template = '事由： <%= newReasonName %>'
					}
					if(hasEditor('newInfo','newWorkTypeCode',configData)){
						attr.subtitle2Template = '任职方式: <%= newWorkTypeName %>'
					}
					changeEditor('newInfo', 'objStr2', attr, mainData);
				}
				if(fileId){
					var fieldArr = getFormFields(mainData)
					fieldArr.push("id")
					
					//主表赋值
					for(var i in res[3].value.tempPosAdjust){
						if(fieldArr.includes(i)){
							_that.$refs.autoform.$set(_that.$refs.autoform.formdata, i, res[3].value.tempPosAdjust[i])
							_that.$set(_that.formdata, i, res[3].value.tempPosAdjust[i])
						}
					}
					//调整前任职岗位信息与岗位拟变动信息
					var origs = _that._.cloneDeep(res[3].value.origs)
					_that.subEditorObj["origInfo"].workList = origs
					_that.$refs.autoform.$set(_that.$refs.autoform.formdata, "objStr1", JSON.stringify(origs))
					_that.$set(_that.formdata, "objStr1", JSON.stringify(origs))
					delete res[3].value.origs
					
					//拟任职岗位与被替换人员信息
					var news = _that._.cloneDeep(res[3].value.news)
					_that.subEditorObj["newInfo"].workList = news
					_that.$refs.autoform.$set(_that.$refs.autoform.formdata, "objStr2", JSON.stringify(news))
					_that.$set(_that.formdata, "objStr2", JSON.stringify(news))
					delete res[3].value.news
					
					//修改时初始化下拉框的值
					_that.$nextTick(function(){
						this.$nextTick(function(){
							if(this.$refs.autoform){
								this.$refs.autoform.initSelectIndex('topinfo', 'zposId')
								this.$refs.autoform.initSelectIndex('title10', 'salaryLevelId')
								this.loadSalaryPos()
								this.loadOrg()
							}
						})
					})
				}
			},options);
		}
	},
	onLoad(options) {
		this.initLoad(options);
	},
	onShow() {
		let _that = this;
		if (_that.$refs.autoform) {
			for (var fieldId in _that.subEditorObj) {
				var editor = _that.subEditorObj[fieldId];
				uni.getStorage({
					key: getWorkCacheKey(fieldId),
					success: function(res) {
						editor.workList = res.data;
						_that.loadSalaryPos()
						uni.removeStorage({
							key: getWorkCacheKey(fieldId)
						});
					}
				});
			}
			uni.getStorage({
				key: _that.userCacheKey,
				success: function(res) {
					if (res.data) {
						let d = res.data;
						var formdata = _that.$refs.autoform.formdata;
						formdata.userId = d.id
						formdata.userName = d.username
						_that.loadOrg(_that.$refs.autoform.formdata.zposId)
						_that.verifyUser(d.id)
						uni.removeStorage({
							key: _that.userCacheKey
						});
					}
				}
			});
			uni.getStorage({
				key: _that.instCacheKey,
				success: function(res) {
					if (res.data) {
						let d = res.data;
						var formdata = _that.$refs.autoform.formdata;
						formdata.newInstId = d.id
						formdata.newInstName = d.instname
						_that.verifyInst(d.id)
						uni.removeStorage({
							key: _that.instCacheKey
						});
					}
				}
			});
		}
	}
};
</script>
<style></style>
